package com.docparser.processor;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 * 处理分数元素。
 */
public class FractionProcessor extends BaseProcessor {
    /**
     * 处理分数元素。
     */
    public static void process(Element fracElement, StringBuilder formula, ProcessorCallback callback) {
        if (fracElement == null) return;
        
        // 提取分子
        NodeList numElements = fracElement.getElementsByTagNameNS(MATH_NAMESPACE, "num");
        StringBuilder numBuilder = new StringBuilder();
        if (numElements.getLength() > 0) {
            NodeList numContent = ((Element) numElements.item(0)).getElementsByTagNameNS(MATH_NAMESPACE, "e");
            if (numContent.getLength() > 0) {
                callback.processElement((Element) numContent.item(0), numBuilder);
            }
        }

        // 提取分母
        NodeList denElements = fracElement.getElementsByTagNameNS(MATH_NAMESPACE, "den");
        StringBuilder denBuilder = new StringBuilder();
        if (denElements.getLength() > 0) {
            NodeList denContent = ((Element) denElements.item(0)).getElementsByTagNameNS(MATH_NAMESPACE, "e");
            if (denContent.getLength() > 0) {
                callback.processElement((Element) denContent.item(0), denBuilder);
            } else {
                // 如果找不到e标签，直接处理den标签的内容
                Element denElement = (Element) denElements.item(0);
                callback.processElement(denElement, denBuilder);
            }
        }
        
        // 格式化分子分母内容
        String numerator = formatFractionContent(numBuilder.toString());
        String denominator = formatFractionContent(denBuilder.toString());

        // 构建分数，直接使用LaTeX格式
        formula.append("\\frac{")
              .append(numerator)
              .append("}{")
              .append(denominator)
              .append("}");
    }
    
    /**
     * 格式化分数内容。
     */
    private static String formatFractionContent(String content) {
        if (content == null || content.trim().isEmpty()) {
            return "1";
        }

        String result = content.trim();

        // 处理负号
        if (result.startsWith("−")) {
            result = "-" + result.substring(1);
        }

        // 清理括号
        if (result.startsWith("{") && result.endsWith("}")) {
            result = result.substring(1, result.length() - 1);
        }

        // 处理特殊字符
        result = result
            .replace("\\{", "{")
            .replace("\\}", "}")
            .replace("\\\\", "\\")
            .replaceAll("\\s+", " ")
            .trim();
            
        return result.isEmpty() ? "1" : result;
    }
}
